package com.pine.dcts.service;

import com.pine.dcts.common.DctsException;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xiaoyuan
 * @create 2021/1/14 20:12
 **/
@Slf4j
public class DefaultTaskExecutor implements TaskExecutor {
    private Thread taskThread;
    private TaskRunner taskRunner;
    private Task task;

    public DefaultTaskExecutor(Task task, TaskRunnerCallback callback) {
        this.task = task;
        taskRunner = new DataxTaskRunner(this.task, callback);
        taskThread = new Thread(taskRunner, String.format("task-%s",
                this.task.getTaskMeta().getTaskId()));
    }

    @Override
    public void start() {
        try {
            this.taskThread.start();
            if (!this.taskThread.isAlive()) {
                throw new DctsException("启动任务运行线程错误");
            }
        } catch (Throwable e) {

        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void stop() {
        if (taskThread.isAlive() && !taskThread.isInterrupted()) {
            taskThread.interrupt();
        }
    }
}
